<?php
require_once "lib/init.php";

$action = $_POST['action'];

switch ($action) {
    case 'login':
	   srv_login();
	break;
    case 'logout':
	   srv_logout();
	break;    
    case 'track.create':
	   srv_track_create();
	break;    
}

function out($data){
    echo json_encode($data);
}

function srv_logout(){
    session_destroy();
    $out['msg']="Logout sucessful !";
    $out['load']='_login.php';  
    out($out);  
}

function srv_login(){
    $email = $_POST['email'];
    $password = $_POST['password'];
    $user = login($email,$password);

    if($user){
        $out['msg']="Login sucessful !";
        $_SESSION['user_id']=$user[0]['id'];
        $_SESSION['user']=$user[0];
        
        $out['load']='_track.php';
    }else{
        $out['error']="User or password incorrect";      
    }   
    out($out);
}

function srv_track_create(){
    
    $data = $_POST;
    $data['user_id']=$_SESSION['user_id'];
    $data['dt']=date('Y-m-d H:i:s');
    $track = create_track($data);  
    if($track){
        $out['msg']= "track saved !";
    }else{
	$out['error']= "track not saved.";
	$out['load']='_login.php';  
    }

    out($out);
    
}